package com.hhhn.wk.main.fragment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseFragment;
import com.hhhn.wk.config.Config;
import com.hhhn.wk.main.tab1.adapter.OnRecyclerviewItemClickListener;
import com.hhhn.wk.main.tab1.adapter.RecyclerViewAdapter;
import com.hhhn.wk.main.tab2.entity.Commodity;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.ToastUtils;
import com.hhhn.wk.widget.irecyclerview.IRecyclerView;
import com.hhhn.wk.widget.irecyclerview.OnLoadMoreListener;
import com.hhhn.wk.widget.irecyclerview.OnRefreshListener;
import com.hhhn.wk.widget.irecyclerview.widget.DensityUtils;
import com.hhhn.wk.widget.irecyclerview.widget.footer.LoadMoreFooterView;
import com.hhhn.wk.widget.irecyclerview.widget.header.BatVsSupperHeaderView;
import com.hhhn.wk.widget.irecyclerview.widget.header.ClassicRefreshHeaderView;
import com.hhhn.wk.widget.wkpulltorefreshlayout.ViewStatus;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class BlankFragment01 extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {
    private int pageHot=1;
    private boolean isWU = false;
    private IRecyclerView iRecyclerView;
    private LoadMoreFooterView loadMoreFooterView;
    private ArrayList<Commodity> mHostArrayList=new ArrayList<>();
    RecyclerViewAdapter adpter;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 1://更多热销
                    dataHost();
                    break;
//                case 2://特价抢购
//                    dataRush();
//                    break;
//                case 3://baner
//                    dataBanner();
//                    break;
//                case 4://获取定位
//                    dataAdress();
//                    break;
            }
        }
    };

    private void dataHost() {
        //初始化recyclerview
        adpter =  new RecyclerViewAdapter(getActivity(),mHostArrayList,onRecyclerviewItemClickListener);
        iRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        iRecyclerView.setAdapter(adpter);
    }

    public BlankFragment01() {
    }
    @Override
    protected int setLayoutResouceId() {
        return R.layout.fragment_blank_fragment01;
    }
    @Override
    protected void initView(View mRootView) {
        iRecyclerView=findViewById(R.id.iRecyclerView);
        // 竖直方向的网格样式，每行四个Item
//       GridLayoutManager   mLayoutManager = new GridLayoutManager(mActivity, 4, OrientationHelper.VERTICAL, false);
//       iRecyclerView.setLayoutManager(mLayoutManager);
        iRecyclerView.setLayoutManager(new GridLayoutManager(mActivity, 3));
        iRecyclerView.setOnRefreshListener(this);
        iRecyclerView.setOnLoadMoreListener(this);
        loadMoreFooterView = (LoadMoreFooterView) iRecyclerView.getLoadMoreFooterView();
        iRecyclerView.post(new Runnable() {
            @Override
            public void run() {
                iRecyclerView.setRefreshing(true);
            }
        });
    }
    @Override
    protected void initData() {

    }
    private OnRecyclerviewItemClickListener onRecyclerviewItemClickListener = new OnRecyclerviewItemClickListener() {
        @Override
        public void onItemClickListener(View v, int position) {
            //这里的view就是我们点击的view  position就是点击的position
            Toast.makeText(getContext()," 点击了 "+position,Toast.LENGTH_SHORT).show();
        }
    };
    @Override
    protected void initClick() {

    }
    @Override
    public void onDestroy() {
        super.onDestroy();

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_toggle_header) {
            toggleRefreshHeader();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    private void toggleRefreshHeader() {
        if (iRecyclerView.getRefreshHeaderView() instanceof BatVsSupperHeaderView) {
            ClassicRefreshHeaderView classicRefreshHeaderView = new ClassicRefreshHeaderView(mActivity);
            classicRefreshHeaderView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, DensityUtils.dip2px(mActivity, 80)));
            // we can set view
            iRecyclerView.setRefreshHeaderView(classicRefreshHeaderView);
            Toast.makeText(mActivity, "Classic style", Toast.LENGTH_SHORT).show();
        } else if (iRecyclerView.getRefreshHeaderView() instanceof ClassicRefreshHeaderView) {
            // we can also set layout
            iRecyclerView.setRefreshHeaderView(R.layout.layout_irecyclerview_refresh_header);
            Toast.makeText(mActivity, "Bat man vs Super man style", Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        if (loadMoreFooterView.canLoadMore() && adpter.getItemCount() > 0) {
            loadMoreFooterView.setStatus(LoadMoreFooterView.Status.LOADING);
            loadMore();
        }
    }
    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        loadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
        refresh();
    }
    private void refresh() {

        pageHot = 1;
        isWU = false;
        mHostArrayList.clear();
        if (adpter != null) {
            adpter.notifyDataSetChanged();
        }
        iRecyclerView.setRefreshing(false);
        getHotJSON();

    }

    private void loadMore() {
        if (isWU) {
            ToastUtils.showShortToast(mActivity, "暂无更多");
            loadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
        } else {
            loadMoreFooterView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    pageHot++;
                    loadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
                    getHotJSON();
                }
            }, 2000);

        }
    }



    //    //获取banner
//    public void getBanner() {
//        RequestParams params = AllPublic.getParamsBanner(mActivity, "/getBanner", false);
//        Log.d(TAG, "获取banner: "+params);
//        //请求
//        x.http().post(params, new Callback.CommonCallback<String>() {
//            @Override  //成功
//            public void onSuccess(String result) {
//                mActivity. LogWk("获取banner:"+result);
//                try {
//                    JSONObject jsonObject= new JSONObject(result);
//                    String reason = jsonObject.getString("code");
//                    if (reason.equals("0")) {
//                        JSONArray data = jsonObject.getJSONArray("data");
//                        Banner banner=null;
//                        for (int i=0;i<data.length();i++){
//                            banner=new Banner();
//                            JSONObject object = data.getJSONObject(i);
//                            String id = object.has("id") ? object.getString("id") : "";
//                            String webUrl = object.has("web_url") ? object.getString("web_url") : "";
//                            String image = object.has("image") ? object.getString("image") : "";
//                            String type = object.has("type") ? object.getString("type") : "";
//                            String title = object.has("title") ? object.getString("title") : "";
//                            banner.setId(id);
//                            banner.setWebUrl(webUrl);
//                            banner.setImage(image);
//                            banner.setType(type);
//                            banner.setTitle(title);
//                            mBanner.add(banner);
//                            handler.sendEmptyMessage(3);
//                        }
//                    }else {
//                        Toast.makeText(mActivity,jsonObject.getString("errMsg"), Toast.LENGTH_SHORT).show();
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//            @Override
//            public void onError(Throwable ex, boolean isOnCallback) {
//                ex.printStackTrace();
//            }
//            @Override
//            public void onCancelled(CancelledException cex) {
//            }
//            @Override
//            public void onFinished() {
//            }
//        });
//    }
//    //加载banner
//    private void dataBanner(){
//        String[] urls = new String[mBanner.size()];
//        for (int i=0;i<mBanner.size();i++){
//            urls[i] =mBanner.get(i).getImage();
//        }
//        adViewpagerUtil = new AdViewpagerUtil(mActivity, viewpager, lydots, 6, 2, urls);
//        adViewpagerUtil.initVps();
////        adViewpagerUtil.setOnAdItemClickListener(new AdViewpagerUtil.OnAdItemClickListener() {
////            @Override
////            public void onItemClick(View v, int flag) {
////                switch (flag){
////                    case 0:
////                        try {
////                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
////                        } catch (Exception ignored) {
////                            toastWk( ignored + "");
////                        }
////                        break;
////                    case 1:
////                        try {
////                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
////                        } catch (Exception ignored) {
////                            toastWk( ignored + "");
////                        }
////                        break;
////                    case 2:
////                        try {
////                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
////                        } catch (Exception ignored) {
////                            toastWk( ignored + "");
////                        }
////                       break;
////                    case 3:
////                        try {
////                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
////                        } catch (Exception ignored) {
////                            toastWk( ignored + "");
////                        }
////                       break;
////                    case 4:
////                        try {
////                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
////                        } catch (Exception ignored) {
////                            toastWk( ignored + "");
////                        }
////                       break;
////                    case 5:
////                        try {
////                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
////                        } catch (Exception ignored) {
////                            toastWk( ignored + "");
////                        }
////                        break;
////                }
////            }
////        });
//    }
    //获取热销产品
    public void getHotJSON() {
        RequestParams params = AllPublic.getParamsProduct(mActivity, "/hotProduct", false);
        params.addParameter("currentPage",pageHot);
        params.addParameter("pageSize", 100);
        Log.d("获取热销产品", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("获取热销产品：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONArray records = jsonObject.getJSONArray("data");
                        Commodity commodity=null;
                        if (records.length() < Config.ROWS) {
                            isWU = true;
                        }
                        for (int i=0;i<records.length();i++){
                            commodity=new Commodity();
                            JSONObject object = records.getJSONObject(i);
                            String commodityid = object.has("id") ? object.getString("id") : "";//id
                            String image = object.has("productPicture") ? object.getString("productPicture") : "";//产品图片
                            String headLine = object.has("name") ? object.getString("name") : "";//产品名称
                            String tradeprice = object.has("wholesalePriceThree") ? object.getString("wholesalePriceThree") : "";//新价格-折扣价格
                            String originalprice = object.has("originalPrice") ? object.getString("originalPrice") : "";//原价-旧价格
                            String inventory = object.has("inventory") ? object.getString("inventory") : "";//商品库存-剩余库存
                            commodity.setCommodityID(commodityid);
                            commodity.setCommodityImg(image);
                            commodity.setCommodityName(headLine);
                            commodity.setPriceOld(originalprice);
                            commodity.setPriceNew(tradeprice);
                            commodity.setInventoryNumber(inventory);
                            mHostArrayList.add(commodity);
                        }
                        handler.sendEmptyMessage(1);
                    }else {
                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();

            }
            @Override
            public void onCancelled(CancelledException cex) {


            }
            @Override
            public void onFinished() {


            }
        });
    }
//    //加载热销产品
//    private void dataHost() {
//        // item宽度
//        int itemWidth = DensityUtil.dip2px(200);
//        // item之间的间隔
//        int itemPaddingH = DensityUtil.dip2px(1);
//        int size = mHostArrayList.size();
//        // 计算GridView宽度
//        int gridviewWidth = size * (itemWidth + itemPaddingH);
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
//                gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
//        mHostGridView.setLayoutParams(params);
//        mHostGridView.setColumnWidth(itemWidth);
//        mHostGridView.setHorizontalSpacing(itemPaddingH);
//        mHostGridView.setStretchMode(GridView.NO_STRETCH);
//        mHostGridView.setNumColumns(size);
//        if (mHostyAdaper==null){
//            mHostyAdaper=new MyAdaper<Commodity>(mHostArrayList,R.layout.item_commoditylist) {
//                @Override
//                public void bindView(ViewHolder holder, Commodity obj, int position) {
//                    holder.setImagechang(R.id.iv_CommodityImg,obj.getCommodityImg());//图片
//                    holder.setText(R.id.iv_CommodityName,obj.getCommodityName());
//                    holder.setText(R.id.tv_priceNew,"￥"+obj.getPriceNew());
//                    holder.setFlags(R.id.tv_priceOld,"￥"+obj.getPriceOld());
//                    holder.setText(R.id.tv_inventoryNumber,"剩余："+obj.getInventoryNumber());
//                }
//            };
//        }else {
//            mHostyAdaper.notifyDataSetChanged();
//        }
//        mHostGridView.setAdapter(mHostyAdaper);
//
//        mActivity.dismissLoad();
//    }
//    //获取特价商品
//    private void getSpecial(){
//        RequestParams params = AllPublic.getParamsProduct(mActivity, "/special", false);
//        params.addParameter("currentPage",pageHot);
//        params.addParameter("pageSize",Config.ROWS);
//        Log.d("获取特价商品", "getJSON: "+params);
//        //请求
//        x.http().post(params, new Callback.CommonCallback<String>() {
//            @Override  //成功
//            public void onSuccess(String result) {
//                Log.d("获取特价商品：", result);
//                try {
//                    JSONObject jsonObject= new JSONObject(result);
//                    String reason = jsonObject.getString("code");
//                    if (reason.equals("0")) {
//                        JSONArray records = jsonObject.getJSONArray("data");
//                        Commodity commodity=null;
//                        for (int i=0;i<records.length();i++){
//                            commodity=new Commodity();
//                            JSONObject object = records.getJSONObject(i);
//                            String commodityid = object.has("id") ? object.getString("id") : "";//id
//                            String image = object.has("product_picture") ? object.getString("product_picture") : "";//产品图片
//                            String headLine = object.has("name") ? object.getString("name") : "";//产品名称
//                            String tradeprice = object.has("wholesale_price_three") ? object.getString("wholesale_price_three") : "";//新价格-折扣价格
//                            String originalprice = object.has("original_price") ? object.getString("original_price") : "";//原价-旧价格
//                            String inventory = object.has("inventory") ? object.getString("inventory") : "";//商品库存-剩余库存
//                            commodity.setCommodityID(commodityid);
//                            commodity.setCommodityImg(image);
//                            commodity.setCommodityName(headLine);
//                            commodity.setPriceOld(originalprice);
//                            commodity.setPriceNew(tradeprice);
//                            commodity.setInventoryNumber(inventory);
//                            mRushArrayList.add(commodity);
//                        }
//                        handler.sendEmptyMessage(2);
//                    }else {
//                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//
//                }
//
//            }
//            @Override
//            public void onError(Throwable ex, boolean isOnCallback) {
//
//                ex.printStackTrace();
//
//            }
//            @Override
//            public void onCancelled(CancelledException cex) {
//
//
//            }
//            @Override
//            public void onFinished() {
//
//
//            }
//        });
//    }
//    //加载特价
//    private void dataRush() {
//        if (mRushAdaper==null){
//            mRushAdaper=new MyAdaper<Commodity>(mRushArrayList,R.layout.item_conlist_rush) {
//                @Override
//                public void bindView(ViewHolder holder, final Commodity obj, int position) {
//                    holder.setImagechang(R.id.iv_CommodityImg,obj.getCommodityImg());//图片
//                    holder.setText(R.id.iv_CommodityName,obj.getCommodityName());
//                    holder.setText(R.id.tv_priceNew,"￥"+obj.getPriceNew());
//                    holder.setFlags(R.id.tv_priceOld,"￥"+obj.getPriceOld());
////                    holder.setOnClickListener(R.id.tv_go, new View.OnClickListener() {
////                        @Override
////                        public void onClick(View view) {
////                            Intent intent=new Intent(mActivity,CommodityXQActivity.class);
////                            intent.putExtra("goods_id",obj.getCommodityID());
////                            startActivity(intent);
////                        }
////                    });
////                    Log.d(TAG, "bindView: "+position);
//                }
//            };
//        }else {
//            mRushAdaper.notifyDataSetChanged();
//        }
//        mListViewRush.setAdapter(mRushAdaper);
//
//    }
//    public class MBroadcastReceiver extends BroadcastReceiver {
//        //接收到广播后自动调用该方法
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            //写入接收广播后的操作
//            Log.d(TAG, "MBroadcastReceiver: 接收广播");
//            handler.sendEmptyMessage(4);
//        }
//    }
//    private void gaode(){
//        //初始化定位
//        mLocationClient = new AMapLocationClient(mActivity.getApplicationContext());
//        mLocationListener = new AMapLocationListener() {
//            @Override
//            public void onLocationChanged(AMapLocation aMapLocation) {
//                if (aMapLocation != null) {
//                    if (aMapLocation.getErrorCode() == 0) {
//                        //可在其中解析amapLocation获取相应内容。
//                        aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
////                        aMapLocation.getLatitude();//获取纬度
////                        aMapLocation.getLongitude();//获取经度
////                        aMapLocation.getAccuracy();//获取精度信息
////                        aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
////                        aMapLocation.getCountry();//国家信息
////                        aMapLocation.getProvince();//省信息
//                        aMapLocation.getCity();//城市信息
//                        aMapLocation.getDistrict();//城区信息
////                        aMapLocation.getStreet();//街道信息
////                        aMapLocation.getStreetNum();//街道门牌号信息
////                        aMapLocation.getCityCode();//城市编码
////                        aMapLocation.getAdCode();//地区编码
////                        aMapLocation.getAoiName();//获取当前定位点的AOI信息
////                        aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
////                        aMapLocation.getFloor();//获取当前室内定位的楼层
////                        aMapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
//                        //获取定位时间
////                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
////                        Date date = new Date(aMapLocation.getTime());
////                        df.format(date);
////                       mActivity. getMyApp().setStr_adress(aMapLocation.getCity());
//                        tv_dingWei.setText(aMapLocation.getDistrict()+"");
//                        Log.d("定位：", "城市信息: "+aMapLocation.getCity());
//                        Log.d("定位：", "城区信息: "+aMapLocation.getDistrict());
//
////                        Log.d("定位：", "获取GPS的当前状态: "+aMapLocation.getGpsAccuracyStatus());
////                        Log.d("定位：", "获取当前室内定位的楼层: "+aMapLocation.getFloor());
//                        toastWk(aMapLocation.getCity());
//                    }else {
//                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
//                        Log.e("AmapError","location Error, ErrCode:"
//                                + aMapLocation.getErrorCode() + ", errInfo:"
//                                + aMapLocation.getErrorInfo());
//                    }
//                }
//            }
//        };
//        //设置定位回调监听
//        mLocationClient.setLocationListener(mLocationListener);
//        //初始化AMapLocationClientOption对象
//        mLocationOption = new AMapLocationClientOption();
//        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        //获取一次定位结果：
//        //该方法默认为false。
//        mLocationOption.setOnceLocation(true);
//        //获取最近3s内精度最高的一次定位结果：
//        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
//        mLocationOption.setOnceLocationLatest(true);
//        //设置是否返回地址信息（默认返回地址信息）
//        mLocationOption.setNeedAddress(true);
//        //给定位客户端对象设置定位参数
//        mLocationClient.setLocationOption(mLocationOption);
//        //启动定位
//        mLocationClient.startLocation();
//    }
}
